import * as React from 'react'
import { Link, useHistory, useParams } from 'react-router-dom'
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Pagination } from 'swiper';
import { ISku } from '../../types'
import style from './style.module.css'
import * as api from '../../services/api'
import "swiper/swiper-bundle.min.css"
import Toast from '../../components/Toast'
SwiperCore.use([Pagination]);

interface Props {
    id: string
}

function Detail(props: Props) {
    const [data, setDate] = React.useState<ISku>()
    const history = useHistory()
    const params = useParams<Props>()
    React.useEffect(() => {
        const getData = async () => {
            let result = await api.getSku(params.id)
            if (result.stat === 'OK') {
                setDate(result.data)
            }
        }
        getData()
    }, [params.id])
    //添加时判断是否登录
    const Add = async () => {
        let result = await api.addCart(params.id)
        if (result.stat === 'OK') {
            Toast("已加入购物车")
        } else {
            Toast("请先登录")
            history.push('/login')
        }
        return
    }

    return (
        <div className={style.page}>
            <main className={style.swiper}>
                <div className={style.swiper_back}>
                    <i className="iconfont icon-back" onClick={() => window.history.back()}></i>
                </div>
                <Swiper
                    className={style.swiperWrap}
                    pagination={{ bulletActiveClass: style.activePage }}
                >
                    {data?.gallery.map((item, index) => {
                        return (
                            <SwiperSlide key={index}>
                                <img alt='' className={style.swiperImg} src={item} />
                            </SwiperSlide>
                        )
                    })}
                </Swiper>
                <div className={style.product}>
                    <div className={style.product_price}>￥{data?.price}</div>
                    <div className={style.product_stock}>库存：{data?.stock}</div>
                    <div className={style.product_title}>{data?.title}</div>
                </div>
                <div className={style.product_detail}>
                    {data?.detail.map((item, index) => {
                        return <img alt='' key={index} src={item} />
                    })}
                </div>
            </main>
            <div className={style.footer}>
                <Link className={style.link} to='/Shopcar'>
                    <i className="iconfont icon-cart"></i>
                    <span>购物车</span>
                </Link>
                <button className={style.addcart} onClick={() => Add()}>
                    加入购物车
                </button>
            </div>
        </div>
    )
}

export default Detail